package com.koushikdutta.async;

import com.koushikdutta.async.callback.DataCallback;

public class DataEmitterReader implements DataCallback {
    static final /* synthetic */ boolean $assertionsDisabled = (!DataEmitterReader.class.desiredAssertionStatus());
    ByteBufferList mPendingData = new ByteBufferList();
    DataCallback mPendingRead;
    int mPendingReadLength;

    public void read(int count, DataCallback callback) {
        if ($assertionsDisabled || this.mPendingRead == null) {
            this.mPendingReadLength = count;
            this.mPendingRead = callback;
            if ($assertionsDisabled || !this.mPendingData.hasRemaining()) {
                this.mPendingData.recycle();
                return;
            }
            throw new AssertionError();
        }
        throw new AssertionError();
    }

    private boolean handlePendingData(DataEmitter emitter) {
        if (this.mPendingReadLength > this.mPendingData.remaining()) {
            return false;
        }
        DataCallback pendingRead = this.mPendingRead;
        this.mPendingRead = null;
        pendingRead.onDataAvailable(emitter, this.mPendingData);
        if ($assertionsDisabled || !this.mPendingData.hasRemaining()) {
            return true;
        }
        throw new AssertionError();
    }

    public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
        if ($assertionsDisabled || this.mPendingRead != null) {
            do {
                bb.get(this.mPendingData, Math.min(bb.remaining(), this.mPendingReadLength - this.mPendingData.remaining()));
                bb.remaining();
                if (!handlePendingData(emitter)) {
                    break;
                }
            } while (this.mPendingRead != null);
            bb.remaining();
            return;
        }
        throw new AssertionError();
    }
}
